package com.papers.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.papers.common.core.domain.PageQuery;
import com.papers.common.core.domain.R;
import com.papers.common.core.domain.dto.RoleDTO;
import com.papers.common.core.page.TableDataInfo;
import com.papers.common.exception.ServiceException;
import com.papers.common.helper.LoginHelper;
import com.papers.common.utils.DateUtils;
import com.papers.common.utils.StringUtils;
import com.papers.juan.domain.TJuanQuestion;
import com.papers.juan.mapper.TJuanQuestionMapper;
import com.papers.system.domain.TJuanChapter;
import com.papers.system.domain.TJuanKnowledge;
import com.papers.system.domain.bo.TJuanKnowledgeBo;
import com.papers.system.domain.dto.TJuanKnowledgeDragDto;
import com.papers.system.domain.dto.TJuanKnowledgeDto;
import com.papers.system.domain.vo.TJuanKnowledgeOutVo;
import com.papers.system.domain.vo.TJuanKnowledgePutVo;
import com.papers.system.domain.vo.TJuanKnowledgeVo;
import com.papers.system.domain.vo.TJuanLeftTreeVo;
import com.papers.system.mapper.*;
import com.papers.system.service.ITJuanKnowledgeService;
import jodd.util.StringUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;


/**
 * 知识点Service业务层处理
 *
 * @author papers
 * @date 2022-10-08
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class TJuanKnowledgeServiceImpl implements ITJuanKnowledgeService {

    private final TJuanKnowledgeMapper baseMapper;

    private final TJuanDepartmentMapper departmentMapper;

    private final TJuanMajorMapper majorMapper;

    private final TJuanCourseMapper courseMapper;

    private final TJuanChapterMapper chapterMapper;

    private final TJuanQuestionMapper juanQuestionMapper;


    /**
     * 查询知识点list
     *
     * @return
     */
    @Override
    public List<TJuanKnowledgeVo> getKnowledgeList(TJuanKnowledgeBo bo) {
        List<TJuanKnowledgeVo> knowledgeList = baseMapper.queryKnowledgeList(bo);
        if (StringUtils.isNotBlank(bo.getChapterId())) {
            return knowledgeList;
        }
        return new ArrayList<>();
    }

    /**
     * 查询知识点树
     *
     * @return
     */
    @Override
    public List<TJuanLeftTreeVo> getKnowledgeTree(TJuanKnowledgeBo bo) {
        // 查询所有的知识点列表
        List<TJuanLeftTreeVo> knowledgeList = baseMapper.getKnowledgeTreeList(bo.getChapterId());
        List<TJuanLeftTreeVo> list = getChildrenList(knowledgeList, "0");
        return list;
    }

    /**
     * 查询侧边树
     *
     * @return
     */
    @Override
    public List<TJuanLeftTreeVo> getLeftTreeList() {
        String departId = "";
        // 查询院系
        List<TJuanLeftTreeVo> leftTreeList = departmentMapper.getDeptTreeList(departId);
        leftTreeList.get(0).setParentId("0");
        // 查询专业
        List<TJuanLeftTreeVo> majorTreeList = majorMapper.getMajorTreeList(departId);
        for (TJuanLeftTreeVo vo : majorTreeList) {
            leftTreeList.add(vo);
        }
        // 查询课程
        List<TJuanLeftTreeVo> courseTreeList = courseMapper.getCourseTreeList(departId);
        courseTreeList.stream().map(item -> {
            String id = item.getId();
            leftTreeList.add(item);
            return id;
        }).collect(Collectors.toList());
        // 查询章节
        // List<TJuanLeftTreeVo> chapterTreeList = chapterMapper.getChapterTreeList(StringUtils.strip(collect.toString(), "[]"));
        // chapterTreeList.forEach(item -> {
        //     leftTreeList.add(item);
        // });

        // 递归获取专业树 课程树 章节树
        List<TJuanLeftTreeVo> list = getChildrenList(leftTreeList, "0");
        return list;
    }

    /**
     * 递归获取 树
     *
     * @param treeList
     * @param id
     * @return
     */
    private List<TJuanLeftTreeVo> getChildrenList(List<TJuanLeftTreeVo> treeList, String id) {
        List<TJuanLeftTreeVo> children = new ArrayList<>();
        for (TJuanLeftTreeVo leftTreeVo : treeList) {
            // 判断该节点的父id，是否与传入的父id相同，相同则递归设置其子节点，并将该节点放入children集合中
            if (StringUtil.equals(leftTreeVo.getParentId(), id)) {
                // 递归设置其子节点
                leftTreeVo.setChildren(getChildrenList(treeList, leftTreeVo.getId()));
                // 放入children集合
                children.add(leftTreeVo);
            }
        }
        return children;
    }

    /**
     * 查询知识点
     */
    @Override
    public TJuanKnowledgeVo queryById(String knowledgeId) {
        return baseMapper.selectVoById(knowledgeId);
    }

    /**
     * 查询知识点列表
     */
    @Override
    public TableDataInfo<TJuanKnowledgeVo> queryPageList(TJuanKnowledgeDto dto, PageQuery pageQuery) {
        // LambdaQueryWrapper<TJuanKnowledge> lqw = buildQueryWrapper(bo);
        Page<TJuanKnowledgeVo> result = baseMapper.getKnowledgeByPage(pageQuery.build(), dto);
        return TableDataInfo.build(result);
    }

    /**
     * 查询知识点列表
     */
    @Override
    public List<TJuanKnowledgeVo> queryList(TJuanKnowledgeBo bo) {
        LambdaQueryWrapper<TJuanKnowledge> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<TJuanKnowledge> buildQueryWrapper(TJuanKnowledgeBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TJuanKnowledge> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getKnowledgeParentId()), TJuanKnowledge::getKnowledgeParentId, bo.getKnowledgeParentId());
        lqw.eq(StringUtils.isNotBlank(bo.getChapterId()), TJuanKnowledge::getChapterId, bo.getChapterId());
        lqw.eq(StringUtils.isNotBlank(bo.getKnowledgeCode()), TJuanKnowledge::getKnowledgeCode, bo.getKnowledgeCode());
        lqw.like(StringUtils.isNotBlank(bo.getKnowledgeName()), TJuanKnowledge::getKnowledgeName, bo.getKnowledgeName());
        lqw.eq(StringUtils.isNotBlank(bo.getKnowledgeContent()), TJuanKnowledge::getKnowledgeContent, bo.getKnowledgeContent());
        lqw.eq(StringUtils.isNotBlank(bo.getKnowledgeDes()), TJuanKnowledge::getKnowledgeDes, bo.getKnowledgeDes());
        lqw.eq(StringUtils.isNotBlank(bo.getCreatedBy()), TJuanKnowledge::getCreatedBy, bo.getCreatedBy());
        lqw.eq(bo.getCreatedTime() != null, TJuanKnowledge::getCreatedTime, bo.getCreatedTime());
        lqw.eq(StringUtils.isNotBlank(bo.getUpdatedBy()), TJuanKnowledge::getUpdatedBy, bo.getUpdatedBy());
        lqw.eq(bo.getUpdatedTime() != null, TJuanKnowledge::getUpdatedTime, bo.getUpdatedTime());
        lqw.eq(StringUtils.isNotBlank(bo.getParentIds()), TJuanKnowledge::getParentIds, bo.getParentIds());
        lqw.eq(TJuanKnowledge::getKnowledgeSort, bo.getKnowledgeSort());
        lqw.eq(TJuanKnowledge::getKnowledgeImportance, bo.getKnowledgeImportance());
        return lqw;
    }

    /**
     * 新增知识点
     */
    @Override
    public Boolean insertByBo(TJuanKnowledgeBo bo) {
        if (StringUtils.isBlank(bo.getChapterId())) {
            throw new ServiceException("请选择章节");
        }
        TJuanKnowledge add = BeanUtil.toBean(bo, TJuanKnowledge.class);
        LambdaQueryWrapper<TJuanKnowledge> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(bo.getKnowledgeParentId()), TJuanKnowledge::getKnowledgeId, bo.getKnowledgeParentId());
        TJuanKnowledge knowledge = baseMapper.selectOne(queryWrapper);
        add.setCreatedBy(LoginHelper.getUsername());
        add.setUpdatedBy(LoginHelper.getUsername());
        add.setCreatedTime(DateUtils.getNowDate());
        add.setUpdatedTime(DateUtils.getNowDate());
        LambdaQueryWrapper<TJuanKnowledge> knowledgeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (StringUtil.equals(bo.getKnowledgeParentId(), "0")) {
            add.setParentIds("0");
            knowledgeLambdaQueryWrapper.eq(TJuanKnowledge::getChapterId, bo.getChapterId())
                    .eq(TJuanKnowledge::getKnowledgeParentId, "0")
                    .orderByDesc(TJuanKnowledge::getKnowledgeCode)
                    .last("LIMIT 1");
        } else {
            add.setParentIds(knowledge.getParentIds() + "," + bo.getKnowledgeParentId());
            knowledgeLambdaQueryWrapper.eq(TJuanKnowledge::getChapterId, bo.getChapterId())
                    .eq(TJuanKnowledge::getKnowledgeParentId, bo.getKnowledgeParentId())
                    .orderByDesc(TJuanKnowledge::getKnowledgeCode)
                    .last("LIMIT 1");
        }
        TJuanKnowledge knowledgeMax = baseMapper.selectOne(knowledgeLambdaQueryWrapper);

        LambdaQueryWrapper<TJuanChapter> lqw = new LambdaQueryWrapper<>();
        lqw.eq(TJuanChapter::getChapterId, bo.getChapterId());
        TJuanChapter tJuanChapter = chapterMapper.selectOne(lqw);
        String newCode;
        Integer newSort;
        if (ObjectUtils.isNull(knowledgeMax)) {
            if (ObjectUtils.isNull(knowledge)) {
                TJuanKnowledge tJuanKnowledge = new TJuanKnowledge();
                tJuanKnowledge.setKnowledgeCode(tJuanChapter.getChapterCode());
                knowledge = tJuanKnowledge;
            }
            newCode = knowledge.getKnowledgeCode() + "01";
            newSort = 1;
        } else {
            List<String> knowledges = baseMapper.selectCodeList(bo);
            int oldCode = Integer.parseInt(knowledgeMax.getKnowledgeCode().substring(knowledgeMax.getKnowledgeCode().length() - 2));
            if (oldCode != knowledges.size()) {
                int currentCode = 01;
                for (String code : knowledges) {
                    if (currentCode != Integer.parseInt(code.substring(knowledgeMax.getKnowledgeCode().length() - 2))) {
                        oldCode = currentCode - 1;
                        break;
                    }
                    currentCode++;
                }
            }
            oldCode++;
            if (oldCode > 99) {
                throw new ServiceException("已达到知识点最大数量，请联系管理员");
            }
            newCode = knowledgeMax.getKnowledgeCode().substring(0, knowledgeMax.getKnowledgeCode().length() - 2).concat(String.format("%02d", oldCode));
            LambdaQueryWrapper<TJuanKnowledge> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(TJuanKnowledge::getChapterId, knowledgeMax.getChapterId())
                    .eq(TJuanKnowledge::getKnowledgeParentId, knowledgeMax.getKnowledgeParentId());
            newSort = baseMapper.selectList(lambdaQueryWrapper).size() + 1;
        }
        add.setKnowledgeCode(newCode);
        //新增的排序
        if (ObjectUtils.isNull(bo.getKnowledgeSort())) {
            add.setKnowledgeSort(newSort);
        }
        //插入的排序
        else {
            add.setKnowledgeSort(bo.getKnowledgeSort());
            LambdaQueryWrapper<TJuanKnowledge> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(TJuanKnowledge::getKnowledgeParentId, bo.getKnowledgeParentId())
                    .eq(TJuanKnowledge::getChapterId, bo.getChapterId())
                    .orderByAsc(TJuanKnowledge::getKnowledgeSort)
                    .ge(TJuanKnowledge::getKnowledgeSort, bo.getKnowledgeSort());
            List<TJuanKnowledge> tJuanKnowledges = baseMapper.selectList(lambdaQueryWrapper);
            for (TJuanKnowledge item : tJuanKnowledges) {
                item.setKnowledgeSort(item.getKnowledgeSort() + 1);
            }
            baseMapper.insertOrUpdateBatch(tJuanKnowledges);
        }
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setKnowledgeId(add.getKnowledgeId());
        }
        return flag;
    }

    /**
     * 修改知识点
     */
    @Override
    public Boolean updateByBo(TJuanKnowledgeBo bo) {
        TJuanKnowledge update = BeanUtil.toBean(bo, TJuanKnowledge.class);
        update.setUpdatedBy(LoginHelper.getUsername());
        update.setUpdatedTime(DateUtils.getNowDate());
        // validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TJuanKnowledge entity) {
        // TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除知识点
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if (isValid) {
            // TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 导入知识点列表
     *
     * @return
     */
    @Override
    public List<TJuanKnowledgePutVo> OutputList(TJuanKnowledgeBo bo) {
        List<String> chapterList = new ArrayList<>();
        if (bo.getTreeType().equals("course")) {
            chapterList = chapterMapper.selectChapterForOutput(bo.getChapterId());
        } else if (bo.getTreeType().equals("chapter")) {
            chapterList.add(bo.getChapterId());
        }
        return baseMapper.outputKnowledge(chapterList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R saveBatch(List<TJuanKnowledgeOutVo> list, String chapterId, String treeType) {
        List<TJuanKnowledgeOutVo> list1 = new ArrayList<>();
        List<TJuanKnowledgeOutVo> list2 = new ArrayList<>();
        for (TJuanKnowledgeOutVo item : list) {
            if (null != item.getKnowledgeCode()) {
                list1.add(item);
            } else {
                list2.add(item);
            }
        }
        list1.addAll(list2);
        String newCode;
        Integer newSort;
        for (TJuanKnowledgeOutVo item : list1) {
            if (null == item.getKnowledgeName()) {
                return R.fail("存在知识点名称为空，请修改");
            }
            if (null == item.getChapterName()) {
                return R.fail("存在章节名称为空，请修改");
            }
            if (null != item.getKnowledgeCode() && item.getKnowledgeCode().length() == 3) {
                item.setKnowledgeCode("0" + item.getKnowledgeCode());
            }
            if (null == item.getChapterCode()) {
                if (null != item.getKnowledgeCode()) {
                    item.setChapterCode(item.getKnowledgeCode().substring(0, 2));
                } else {
                    item.setChapterCode("01");
                }
            } else {
                if (item.getChapterCode().length() != 2) {
                    item.setChapterCode("0" + item.getChapterCode());
                }
            }
            if (null != item.getKnowledgeCode() && (item.getKnowledgeCode().length() != 4
                    || !item.getKnowledgeCode().substring(0, 2).equals(item.getChapterCode())
                    || item.getKnowledgeCode().substring(2).equals("00"))) {
                return R.fail("存在知识点编号与章节不匹配，请修改");
            }
            //查询对应章节信息
            TJuanChapter chapter = new TJuanChapter();
            if (treeType.equals("chapter")) {
                LambdaQueryWrapper<TJuanChapter> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(TJuanChapter::getChapterId, chapterId);
                chapter = chapterMapper.selectOne(queryWrapper);
                item.setKnowledgeCode(null);
                item.setChapterCode(chapter.getChapterCode());
            } else if (treeType.equals("course")) {
                LambdaQueryWrapper<TJuanChapter> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(TJuanChapter::getChapterCode, item.getChapterCode())
                        .eq(TJuanChapter::getCourseId, chapterId);
                chapter = chapterMapper.selectOne(queryWrapper);
                if (null == chapter) {
                    TJuanChapter tJuanChapter = new TJuanChapter();
                    tJuanChapter.setChapterCode(item.getChapterCode());
                    tJuanChapter.setChapterName(item.getChapterName());
                    tJuanChapter.setParentId("0");
                    tJuanChapter.setChapterParentId("0");
                    LambdaQueryWrapper<TJuanChapter> chapterLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    chapterLambdaQueryWrapper.eq(TJuanChapter::getCourseId, chapterId);
                    tJuanChapter.setChapterSort(chapterMapper.selectCount(chapterLambdaQueryWrapper).intValue());
                    tJuanChapter.setCourseId(chapterId);
                    chapterMapper.insert(tJuanChapter);
                    chapter = tJuanChapter;
                }
            }

            //查询当前章节下的最大知识点
            LambdaQueryWrapper<TJuanKnowledge> knowledgeLambdaQueryWrapper = new LambdaQueryWrapper<>();
            knowledgeLambdaQueryWrapper.eq(TJuanKnowledge::getChapterId, chapter.getChapterId())
                    .eq(TJuanKnowledge::getKnowledgeParentId, "0")
                    .orderByDesc(TJuanKnowledge::getKnowledgeCode)
                    .last("LIMIT 1");
            TJuanKnowledge knowledgeMax = baseMapper.selectOne(knowledgeLambdaQueryWrapper);

            LambdaQueryWrapper<TJuanKnowledge> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(TJuanKnowledge::getChapterId, chapter.getChapterId())
                    .eq(TJuanKnowledge::getKnowledgeParentId, "0");
            //没有code
            if (ObjectUtils.isEmpty(item.getKnowledgeCode())) {
                if (ObjectUtils.isNull(knowledgeMax)) {
                    newCode = item.getChapterCode() + "01";
                    newSort = 1;
                } else {
                    TJuanKnowledgeBo bo = new TJuanKnowledgeBo();
                    bo.setChapterId(chapter.getChapterId());
                    bo.setKnowledgeParentId("0");
                    List<String> knowledges = baseMapper.selectCodeList(bo);
                    int oldCode = Integer.parseInt(knowledgeMax.getKnowledgeCode().substring(knowledgeMax.getKnowledgeCode().length() - 2));
                    if (oldCode != knowledges.size()) {
                        int currentCode = 01;
                        for (String code : knowledges) {
                            if (currentCode != Integer.parseInt(code.substring(code.length() - 2))) {
                                oldCode = currentCode - 1;
                                break;
                            }
                            currentCode++;
                        }
                    }
                    oldCode++;
                    if (oldCode > 99) {
                        return R.fail("已达到知识点最大数量，请联系管理员");
                    }
                    newCode = chapter.getChapterCode() + String.format("%02d", oldCode);
                    newSort = baseMapper.selectList(lambdaQueryWrapper).size() + 1;
                }
                item.setKnowledgeCode(newCode);
                item.setKnowledgeParentId("0");
                item.setParentIds("0");
                item.setCreatedBy(LoginHelper.getUsername());
                item.setCreatedTime(DateUtils.getNowDate());
            }
            //有code
            else {
                LambdaQueryWrapper<TJuanKnowledge> lqw = new LambdaQueryWrapper<>();
                lqw.eq(TJuanKnowledge::getChapterId, chapter.getChapterId())
                        .eq(TJuanKnowledge::getKnowledgeCode, item.getKnowledgeCode());
                TJuanKnowledge knowledge = baseMapper.selectOne(lqw);
                //重复，更新信息
                if (codeVerify(chapter.getChapterId(), item.getKnowledgeCode())) {
                    item.setKnowledgeId(knowledge.getKnowledgeId());
                    item.setKnowledgeParentId(knowledge.getKnowledgeParentId());
                    newSort = knowledge.getKnowledgeSort();
                }
                //没有重复，新增
                else {
                    item.setCreatedBy(LoginHelper.getUsername());
                    item.setCreatedTime(DateUtils.getNowDate());
                    item.setKnowledgeParentId("0");
                    newSort = baseMapper.selectList(lambdaQueryWrapper).size() + 1;
                }
            }
            item.setKnowledgeSort(newSort);
            item.setChapterId(chapter.getChapterId());
            item.setUpdatedBy(LoginHelper.getUsername());
            item.setUpdatedTime(DateUtils.getNowDate());
            TJuanKnowledge tJuanKnowledge = new TJuanKnowledge();
            BeanUtils.copyProperties(item, tJuanKnowledge);
            baseMapper.insertOrUpdate(tJuanKnowledge);
        }
        return R.ok("导入成功");
    }

    /**
     * 验证编码是否唯一
     *
     * @param code
     * @return
     */
    public boolean codeVerify(String chapterId, String code) {
        LambdaQueryWrapper<TJuanKnowledge> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TJuanKnowledge::getChapterId, chapterId)
                .eq(TJuanKnowledge::getKnowledgeCode, code);
        List<TJuanKnowledge> tJuanKnowledges = baseMapper.selectList(queryWrapper);
        for (TJuanKnowledge juanKnowledge : tJuanKnowledges) {
            if (null != code && code.equals(juanKnowledge.getKnowledgeCode())) {
                return true;
            }
        }
        return false;
    }

    @Override
    public List<TJuanLeftTreeVo> getCourseTreeList(String majorId) {
        //查看本人的角色
        List<RoleDTO> roles = LoginHelper.getRoles();
        //如果角色有且只有一个教员，则他只能看到他自己创建的题库
        String userName = null;
        if (roles.size() == 1) {
            if ("教员".equals(roles.get(0).getRoleName())) {
                userName = LoginHelper.getUsername();
            }
        }
        List<TJuanLeftTreeVo> courseTreeList = courseMapper.getLeftTree(majorId, userName);
        return courseTreeList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<Void> deleteKnowledge(String[] knowledgeIds) {
        //需要删除的子节点
        List<TJuanKnowledge> knowledgeDelete = new ArrayList<>();
        List<TJuanQuestion> questionDelete = new ArrayList<>();
        //查看章节是否存在子节点、知识点、题目
        for (String id : knowledgeIds) {
            LambdaQueryWrapper<TJuanKnowledge> knowledge = new LambdaQueryWrapper<>();
            knowledge.eq(TJuanKnowledge::getKnowledgeParentId, id);
            List<TJuanKnowledge> knowledgeData = baseMapper.selectList(knowledge);
            if (CollectionUtils.isNotEmpty(knowledgeData)) {
//                return R.fail("该知识点存在子节点未删除!");
                //存在子节点，则直接删除
                knowledgeDelete.addAll(knowledgeData);
                //查询子节点的题目
                LambdaQueryWrapper<TJuanQuestion> questionChildren = new LambdaQueryWrapper<>();
                questionChildren.in(TJuanQuestion::getKnowledgeId, knowledgeData);
                List<TJuanQuestion> questionChildrenDelete = juanQuestionMapper.selectList(questionChildren);
                questionDelete.addAll(questionChildrenDelete);
            }
            LambdaQueryWrapper<TJuanQuestion> question = new LambdaQueryWrapper<>();
            question.eq(TJuanQuestion::getKnowledgeId, id);
            List<TJuanQuestion> questionData = juanQuestionMapper.selectList(question);
            if (CollectionUtils.isNotEmpty(questionData)) {
//                return R.fail("该知识点存在题目未删除");
                questionDelete.addAll(questionData);
            }
        }
        //删除
        if (CollectionUtils.isNotEmpty(knowledgeDelete)) {
            baseMapper.deleteBatchIds(knowledgeDelete);
        }
        if (CollectionUtils.isNotEmpty(questionDelete)) {
            juanQuestionMapper.deleteBatchIds(questionDelete);
        }

        LambdaQueryWrapper<TJuanKnowledge> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(TJuanKnowledge::getKnowledgeId, knowledgeIds);
        List<TJuanKnowledge> knowledges = baseMapper.selectList(queryWrapper);
        for (TJuanKnowledge tJuanKnowledge : knowledges) {
            LambdaQueryWrapper<TJuanKnowledge> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(TJuanKnowledge::getKnowledgeParentId, tJuanKnowledge.getKnowledgeParentId())
                    .eq(TJuanKnowledge::getChapterId, tJuanKnowledge.getChapterId())
                    .ge(TJuanKnowledge::getKnowledgeSort, tJuanKnowledge.getKnowledgeSort());
            List<TJuanKnowledge> tJuanKnowledges = baseMapper.selectList(lambdaQueryWrapper);
            for (TJuanKnowledge item : tJuanKnowledges) {
                item.setKnowledgeSort(item.getKnowledgeSort() - 1);
            }
            baseMapper.insertOrUpdateBatch(tJuanKnowledges);
        }

        int flag = baseMapper.deleteBatchIds(Arrays.asList(knowledgeIds));
        if (flag > 0) {
            return R.ok("删除成功!");
        }
        return R.fail("删除失败!");
    }

    @Override
    public int KnowledgeCodeUnique(TJuanKnowledgeBo bo) {
        LambdaQueryWrapper<TJuanKnowledge> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TJuanKnowledge::getKnowledgeCode, bo.getKnowledgeCode());
        queryWrapper.last("LIMIT 1");
        TJuanKnowledgeVo tJuanKnowledgeVo = baseMapper.selectVoOne(queryWrapper);
        /*如存在相同code的对象，返回0*/
        if (tJuanKnowledgeVo == null) {
            return 1;
        }
        if (tJuanKnowledgeVo.getKnowledgeId().equals(bo.getKnowledgeId())) {
            return 1;
        }
        return 0;
    }

    /**
     * 拖拽排序
     *
     * @param dto
     * @return
     */
    @Override
    public boolean dragSort(TJuanKnowledgeDragDto dto) {
        // 获取当前sort
        Integer currSort = dto.getCurrentSort();
        // 获取目标sort
        Integer targetSort = dto.getTargetSort();
        LambdaQueryWrapper<TJuanKnowledge> lqw = new LambdaQueryWrapper<>();
        lqw.eq(TJuanKnowledge::getKnowledgeSort, currSort)
                .eq(TJuanKnowledge::getChapterId, dto.getChapterId())
                .eq(TJuanKnowledge::getKnowledgeParentId, dto.getKnowledgeParentId());
        TJuanKnowledge tJuanKnowledge = baseMapper.selectOne(lqw);
        tJuanKnowledge.setKnowledgeSort(targetSort);
        // 获取当前和目标之间的数据
        QueryWrapper<TJuanKnowledge> queryWrapper = new QueryWrapper<>();
        if (targetSort < currSort) {
            queryWrapper.eq("CHAPTER_ID", dto.getChapterId())
                    .eq("KNOWLEDGE_PARENT_ID", dto.getKnowledgeParentId())
                    .between("KNOWLEDGE_SORT", targetSort, currSort);
        } else {
            queryWrapper.eq("CHAPTER_ID", dto.getChapterId())
                    .eq("KNOWLEDGE_PARENT_ID", dto.getKnowledgeParentId())
                    .between("KNOWLEDGE_SORT", currSort, targetSort);
        }
        List<TJuanKnowledge> list = baseMapper.selectList(queryWrapper);
        list = list.stream().filter(item -> item.getKnowledgeSort() != currSort).map(item -> {
            if (targetSort < currSort) {
                item.setKnowledgeSort(item.getKnowledgeSort() + 1);
            } else {
                item.setKnowledgeSort(item.getKnowledgeSort() - 1);
            }
            return item;
        }).collect(Collectors.toList());
        list.add(tJuanKnowledge);
        list.stream().sorted(Comparator.comparing(TJuanKnowledge::getKnowledgeSort));
        if (baseMapper.insertOrUpdateBatch(list)) {
            return true;
        }
        ;
        return false;
    }

}
